package net.jxtz.jxtzos.landtax;

import com.alibaba.fastjson.JSON;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import net.jxtz.jxtzos.entity.landtax.Residential;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.SerializableEntity;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Controller;

import java.io.InputStream;
import java.util.List;

/**
 * @author a123
 */

@Slf4j
@Component
public class SyncToMobileServe {

    private final static String BASE_URL = "http://landtax.wechat.jxtz.net/land_tax";

    @SneakyThrows
    public void add(Residential residential){
        String s1 = JSON.toJSONString(residential);
        String s = httpPost(BASE_URL + "/add", s1);
        log.info("SyncToMobileServe.add() ==> " + s);
    }

    public void addBatch(List<Residential> residentials){
        String s = JSON.toJSONString(residentials);
        String s1 = httpPost(BASE_URL + "/addBatch", s);
        log.info(s1);
    }

    public void update(Residential residential){
        String s = JSON.toJSONString(residential);
        String s1 = httpPost(BASE_URL + "/update", s);
        log.info("SyncToMobileServe.update() ==> " + s1);
    }

    public void updateBatch(List<Residential> residentials){
        String s = JSON.toJSONString(residentials);
        String s1 = httpPost(BASE_URL + "/updateBatch", s);
        log.info("SyncToMobileServe.updateBatch() ==> " + s1);
    }


    @SneakyThrows
    private static String httpPost(String url, String json){
        CloseableHttpClient httpClient = HttpClients.createDefault();
        HttpPost httpPost = new HttpPost(url);
        StringEntity stringEntity = new StringEntity(json, "UTF-8");
        stringEntity.setContentEncoding("UTF-8");
        stringEntity.setContentType("application/json");
        httpPost.setEntity(stringEntity);
        httpPost.setHeader("User-Agent", "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.114 Safari/537.36");
        CloseableHttpResponse response = httpClient.execute(httpPost);
        return EntityUtils.toString(response.getEntity());
    }

}
